package code

import (
	"database/sql/driver"
	"errors"
	"fmt"
	json "github.com/json-iterator/go"
	"gorm.io/gorm"
	"time"
)

type Model struct {
	Id        uint           `gorm:"primaryKey"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

type MapIntJSONB []interface{}

func (dj MapIntJSONB) Value() (driver.Value, error) {
	return json.Marshal(dj)
}

func (dj *MapIntJSONB) Scan(value interface{}) error {
	b, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("[]byte assertion failed")
	}

	return json.Unmarshal(b, &dj)
}

type SliceUint []uint

func (dj SliceUint) Value() (driver.Value, error) {
	return json.Marshal(dj)
}

func (dj *SliceUint) Scan(value interface{}) error {
	b, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("[]byte assertion failed")
	}

	return json.Unmarshal(b, &dj)
}

type SliceInt []int

func (dj SliceInt) Value() (driver.Value, error) {
	return json.Marshal(dj)
}

func (dj *SliceInt) Scan(value interface{}) error {
	b, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("[]byte assertion failed")
	}

	return json.Unmarshal(b, &dj)
}

type SliceString []string

func (dj SliceString) Value() (driver.Value, error) {
	return json.Marshal(dj)
}

func (dj *SliceString) Scan(value interface{}) error {
	b, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("[]byte assertion failed")
	}

	return json.Unmarshal(b, &dj)
}

type MapJSONB map[string]interface{}

func (maj MapJSONB) Value() (driver.Value, error) {
	return json.Marshal(maj)
}

func (maj *MapJSONB) Scan(value interface{}) error {
	b, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("[]byte assertion failed")
	}
	return json.Unmarshal(b, &maj)
}

type MapArrayJSONB []map[string]interface{}

func (maj MapArrayJSONB) Value() (driver.Value, error) {
	return json.Marshal(maj)
}

func (maj *MapArrayJSONB) Scan(value interface{}) error {
	b, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("[]byte assertion failed")
	}
	return json.Unmarshal(b, &maj)
}

type Account struct {
	Type          int    `json:"type"`           // 0 -> alipay 1 -> wechat
	IncomeAccount string `json:"income_account"` //收款方账号信息
	PayeeName     string `json:"payee_name"`     //收款人名称/姓名
}

func (a Account) Value() (driver.Value, error) {
	return json.Marshal(&a)
}

func (a *Account) Scan(value interface{}) error {
	b, ok := value.([]byte)
	if !ok {
		return errors.New("type assertion to []byte failed")
	}
	return json.Unmarshal(b, &a)
}

type ImportError struct {
	Sheet  string `json:"sheet"`
	Number int    `json:"number"`
	Cell   int    `json:"cell"`
	Reason string `json:"reason"`
}
